package com.atguigu.gmall.user.controller;


import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")///api/user/passport/login
public class PassportController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //查询
        UserInfo info = userService.login(userInfo);
        if(null != info){
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            Map result = new HashMap<>();
            result.put("name",info.getName());
            result.put("nickName",info.getNickName());
            result.put("token", token);
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token,info.getId().toString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(result).message("登录成功");
        }else{
            //失败
            return Result.fail().message("用户名或密码错误");
        }
    }
    //
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX + request.getHeader("token"));
        return Result.ok();
    }
}
